package com.fac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fac.constant.CommonConstant;
import com.fac.constant.EquipmentStatus;
import com.fac.constant.ExceptionConstant;
import com.fac.constant.OrderStatus;
import com.fac.dto.LeaseOrderCreateDTO;
import com.fac.dto.LeaseOrderPageQueryDTO;
import com.fac.dto.LeaseOrderReturnDTO;
import com.fac.entity.Equipment;
import com.fac.entity.LeaseOrder;
import com.fac.entity.Users;
import com.fac.exception.BusinessException;
import com.fac.mapper.EquipmentMapper;
import com.fac.mapper.LeaseOrderMapper;
import com.fac.mapper.UsersMapper;
import com.fac.result.PageResult;
import com.fac.service.LeaseOrderService;
import com.fac.vo.LeaseOrderCreateVO;
import com.fac.vo.LeaseOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租赁订单服务实现类
 */
@Service
@Slf4j
public class LeaseOrderServiceImpl implements LeaseOrderService {

    @Autowired
    private LeaseOrderMapper leaseOrderMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    /**
     * 分页查询租赁订单
     *
     * @param queryDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult pageQuery(LeaseOrderPageQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<LeaseOrder> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加订单状态查询条件
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(LeaseOrder::getOrderStatus, queryDTO.getStatus());
        }

        // 添加用户ID查询条件
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(LeaseOrder::getUserId, queryDTO.getUserId());
        }

        // 添加设备ID查询条件
        if (queryDTO.getEquipmentId() != null) {
            queryWrapper.eq(LeaseOrder::getEquipmentId, queryDTO.getEquipmentId());
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(LeaseOrder::getCreatedAt);

        // 创建分页对象
        Page<LeaseOrder> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());

        // 执行分页查询
        Page<LeaseOrder> orderPage = leaseOrderMapper.selectPage(page, queryWrapper);

        // 转换为VO列表
        List<LeaseOrderVO> voList = orderPage.getRecords().stream()
                .map(order -> {
                    // 查询用户信息
                    Users user = usersMapper.selectById(order.getUserId());
                    // 查询设备信息
                    Equipment equipment = equipmentMapper.selectById(order.getEquipmentId());

                    return LeaseOrderVO.builder()
                            .orderId(order.getOrderId())
                            .code(order.getCode())
                            .userName(user != null ? user.getRealName() : null)
                            .equipmentName(equipment != null ? equipment.getName() : null)
                            .startTime(order.getStartTime())
                            .expectedReturnTime(order.getExpectedReturnTime())
                            .actualReturnTime(order.getActualReturnTime())
                            .leaseDays(order.getLeaseDays())
                            .chargeType(order.getChargeType())
                            .leaseFee(order.getLeaseFee())
                            .deposit(order.getDeposit())
                            .orderStatus(order.getOrderStatus())
                            .depositStatus(order.getDepositStatus())
                            .contactPerson(order.getContactPerson())
                            .contactPhone(order.getContactPhone())
                            .build();
                })
                .collect(Collectors.toList());

        return new PageResult(orderPage.getTotal(), voList);
    }

    /**
     * 确认归还设备
     *
     * @param orderId 订单ID
     * @param returnDTO 归还信息
     * @return 更新后的订单信息
     */
    @Override
    @Transactional
    public LeaseOrderVO confirmReturn(Long orderId, LeaseOrderReturnDTO returnDTO) {
        // 查询订单信息
        LeaseOrder order = leaseOrderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException(ExceptionConstant.ERROR_ORDER_NOT_FOUND);
        }

        // 检查订单状态
        if (order.getOrderStatus() != OrderStatus.LEASING) {
            throw new BusinessException(ExceptionConstant.ERROR_ORDER_STATUS);
        }

        // 更新订单信息
        LeaseOrder updateOrder = new LeaseOrder();
        updateOrder.setOrderId(orderId);
        updateOrder.setActualReturnTime(returnDTO.getActualReturnTime());
        updateOrder.setOrderStatus(OrderStatus.COMPLETED);
        updateOrder.setRemarks(returnDTO.getRemarks());

        // 更新订单
        leaseOrderMapper.updateById(updateOrder);

        // 更新设备状态为闲置
        Equipment updateEquipment = new Equipment();
        updateEquipment.setEquipmentId(order.getEquipmentId());
        updateEquipment.setStatus(EquipmentStatus.IDLE);

        // 更新设备
        equipmentMapper.updateById(updateEquipment);

        // 查询更新后的订单信息
        order = leaseOrderMapper.selectById(orderId);
        Users user = usersMapper.selectById(order.getUserId());
        Equipment equipment = equipmentMapper.selectById(order.getEquipmentId());

        // 转换为VO
        return LeaseOrderVO.builder()
                .orderId(order.getOrderId())
                .code(order.getCode())
                .userName(user != null ? user.getRealName() : null)
                .equipmentName(equipment != null ? equipment.getName() : null)
                .startTime(order.getStartTime())
                .expectedReturnTime(order.getExpectedReturnTime())
                .actualReturnTime(order.getActualReturnTime())
                .leaseDays(order.getLeaseDays())
                .chargeType(order.getChargeType())
                .leaseFee(order.getLeaseFee())
                .deposit(order.getDeposit())
                .orderStatus(order.getOrderStatus())
                .depositStatus(order.getDepositStatus())
                .contactPerson(order.getContactPerson())
                .contactPhone(order.getContactPhone())
                .build();
    }

    /**
     * 创建租赁订单
     *
     * @param createDTO 创建订单信息
     * @return 创建结果
     */
    @Override
    @Transactional
    public LeaseOrderCreateVO create(LeaseOrderCreateDTO createDTO) {
        // 检查设备是否存在
        Equipment equipment = equipmentMapper.selectById(createDTO.getEquipmentId());
        if (equipment == null) {
            throw new BusinessException(ExceptionConstant.EQUIPMENT_NOT_FOUND);
        }

        // 检查设备状态
        if (equipment.getStatus() != EquipmentStatus.IDLE) {
            throw new BusinessException(ExceptionConstant.EQUIPMENT_NOT_LEASABLE);
        }

        // 计算租赁天数
        long days = Duration.between(createDTO.getStartTime(), createDTO.getExpectedReturnTime()).toDays();
        if (days <= 0) {
            throw new BusinessException(ExceptionConstant.LEASE_TIME_INCORRECT);
        }

        // TODO: 支付链接、租赁费用、租赁期限等信息应该从数据库中获取
        // 计算租赁费用（示例：每天100元）
        BigDecimal dailyRate = new BigDecimal("100");
        BigDecimal leaseFee = dailyRate.multiply(new BigDecimal(days));

        // 设置押金（示例：设备价值的20%）
        BigDecimal deposit = equipment.getValue().multiply(new BigDecimal("0.2"));

        // 生成订单编号
        String orderCode = generateOrderCode();

        // 创建订单
        LeaseOrder order = LeaseOrder.builder()
                .code(orderCode)
                // TODO: 这里应该从当前登录用户中获取用户ID
//                .userId(BaseContext.getCurrentId())
                .userId(1L)
                .equipmentId(createDTO.getEquipmentId())
                .startTime(createDTO.getStartTime())
                .expectedReturnTime(createDTO.getExpectedReturnTime())
                .leaseDays((int) days)
                .chargeType(createDTO.getChargeType())
                .leaseFee(leaseFee)
                .deposit(deposit)
                .orderStatus(OrderStatus.PENDING_PAYMENT)
                .depositStatus(0)
                .contactPerson(createDTO.getContactPerson())
                .contactPhone(createDTO.getContactPhone())
                .build();

        // 保存订单
        leaseOrderMapper.insert(order);

        // 更新设备状态为使用中
        equipment.setStatus(EquipmentStatus.IN_USE);
        equipmentMapper.updateById(equipment);

        // TODO: 这里应该返回支付链接
        // 生成支付链接（示例）
        String paymentUrl = "https://payment.example.com/pay/" + order.getOrderId();

        // 返回结果
        return LeaseOrderCreateVO.builder()
                .orderId(order.getOrderId())
                .code(order.getCode())
                .equipmentName(equipment.getName())
                .leaseDays(order.getLeaseDays())
                .leaseFee(order.getLeaseFee())
                .deposit(order.getDeposit())
                .orderStatus(order.getOrderStatus())
                .paymentUrl(paymentUrl)
                .build();
    }

    /**
     * 生成订单编号
     * 格式：L + 年月日 + 3位序号
     */
    private String generateOrderCode() {
        LocalDateTime now = LocalDateTime.now();
        String date = String.format("%tY%<tm%<td", now);
        
        // 查询当天最大序号
        String prefix = "L" + date;
        LambdaQueryWrapper<LeaseOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(LeaseOrder::getCode, prefix)
                .orderByDesc(LeaseOrder::getCode)
                .last("LIMIT 1");
        
        LeaseOrder lastOrder = leaseOrderMapper.selectOne(queryWrapper);
        
        int sequence = 1;
        if (lastOrder != null) {
            String lastCode = lastOrder.getCode();
            sequence = Integer.parseInt(lastCode.substring(9)) + 1;
        }
        
        return String.format("%s%03d", prefix, sequence);
    }
} 